package com.wocai.jrt.orgadmin.product.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductGrade;
import com.wocai.jrt.orgadmin.product.service.spi.ProductGradeService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;

/**
 * 产品档次控制器
 * 
 * @author yinlei
 * @date 2015-8-22 11:23:50
 */
@Controller
@RequestMapping("/productGrade")
public class ProductGradeAction extends GenericAction<ProductGrade> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductGradeAction.class);

	@Inject
	private ProductGradeService productGradeServiceImpl;

	@Inject
	private ProductService productServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获得产品档次List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 产品档次List
	 */
	@RequestMapping("/list/{productId}")
	public String initial(@PathVariable("productId") String productId, Map<String, Object> maps) {
		try {
			Product product = productServiceImpl.get(productId);
			maps.put("product", product);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "product/productGrade";
	}

	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody ProductGrade model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request ProductGrade query, param = [{}]", JSON.toJSONString(model));

			int size = productGradeServiceImpl.countBy(model);

			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			List<ProductGrade> list = productGradeServiceImpl.pagedList(model);

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request ProductGrade query error, msg = [{}]", e.getMessage());
		}

		return map;
	}

	/**
	 * 根据Id获得产品档次实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 产品档次实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public ProductGrade get(String id) {
		ProductGrade model = null;
		try {
			model = productGradeServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add() {
		return "productGrade/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(@RequestBody @Valid ProductGrade model, BindingResult errors) {
		JsonBean bean = new JsonBean();
		try {
			if (errors.hasErrors()) {
				bean.setCode(0);
				bean.setMessage("parameter valid failure！");
				LOGGER.error("parameter valid failure, model = [{}]", JSON.toJSONString(model));
				return bean;
			}

			ProductGrade pgParam = new ProductGrade();
			pgParam.setProductId(model.getProductId());
			int count = productGradeServiceImpl.countBy(pgParam);
			if (count >= 5) {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
				return bean;
			}

			model.setId(ObjectId.get().toString());
			model.setSubScopeStart(model.getSubScopeStart() * 10000);
			model.setSubScopeEnd(model.getSubScopeEnd() * 10000);
			int result = productGradeServiceImpl.save(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 查看产品档次详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 产品档次详情页
	 */
	@RequestMapping("/detail")
	public String detail(ProductGrade model, Map<String, Object> maps) {
		try {
			model = productGradeServiceImpl.get(model.getId());
			maps.put("model", model);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "productGrade/detail";
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(ProductGrade model, Map<String, Object> maps) {
		model = productGradeServiceImpl.get(model.getId());
		maps.put("model", model);
		return "productGrade/edit";
	}

	/**
	 * 更新产品档次信息
	 * 
	 * @param model
	 *            要更新的产品档次信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(@Valid @RequestBody ProductGrade model, BindingResult errors) {
		JsonBean bean = new JsonBean();
		try {
			
			if (errors.hasErrors()) {
				bean.setCode(0);
				bean.setMessage("parameter valid failure！");
				LOGGER.error("parameter valid failure, model = [{}]", JSON.toJSONString(model));
				return bean;
			}
			
			model.setSubScopeStart(model.getSubScopeStart() * 10000);
			model.setSubScopeEnd(model.getSubScopeEnd() * 10000);
			int result = productGradeServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除产品档次信息
	 * 
	 * @param id
	 *            要删除的产品档次ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			int result = productGradeServiceImpl.deleteById(id);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
}
